package com.ckm.creator;

import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClients;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import java.util.Collections;

@Slf4j
public class MongoSourceCreatorImpl implements MongoSourceCreator{
    @Override
    public MongoDatabaseFactory createMongoSource(MongoProperties mongoProperties) {
        String uri = mongoProperties.getUri();
        log.info("正在初始化mongoDatabaseFactory");
        if (uri == null || uri.isEmpty()){
            String host = mongoProperties.getHost();
            Integer port = mongoProperties.getPort();
            if (host == null|| host.isEmpty()||port==null){
                ServerAddress serverAddress = new ServerAddress(host, port);
                MongoClientSettings.Builder builder = MongoClientSettings.builder()
                        .applyToClusterSettings(b -> b.hosts(Collections.singletonList(serverAddress)))
                        .retryWrites(false);
                if (mongoProperties.getUsername()!=null&&!mongoProperties.getUsername().isEmpty()){
                    builder.credential(MongoCredential.createAwsCredential(mongoProperties.getUsername(),mongoProperties.getPassword()));
                };
                return new SimpleMongoClientDatabaseFactory(MongoClients.create(builder.build()), mongoProperties.getDatabase());
            }
            throw new RuntimeException("host或port为空，创建失败");
        }else {
            return new SimpleMongoClientDatabaseFactory(uri);
        }
    }
}
